<?php
/**
* 即时通讯 模型
* @author steven
*/

require_once ('iIM.php');

class IM implements iIM
{
    
    /**
    * @var      string
    */
    private $_username;
    
    /**
    * @var      string
    */
    private $_password;
    
    /**
    * @var      string
    */
    protected $_url = "http://localhost:8080/Service/IM";
    
    /**
    * @var      string
    */
    protected $_domain = "mq";
    
    /**
    * 接收消息的用户
    * @var      string
    */
    private $_to;

    /**
    * 取得好友列表
    * @return   array
    */
    public function getRoster()
    {
    	$msg = $this->_parseXML($this->_send($this->_xml("roster")));
    	return $msg['body'];
    }
    
    /**
    * 发送信息
    * @param    string $message    
    * @return   boolean
    */
    public function sendMessage($message)
    {
    	$this->_message = $message;
    	$msg = $this->_parseXML($this->_send($this->_xml("send")));
    	return $msg['body'];	
    }
    
    /**
    * 取得消息
    * @return   array
    */
    public function getMessage()
    {
    	$msg = $this->_parseXML($this->_send($this->_xml("receive")));
    	if($msg['body']['count'] == 1){
    		$tmp = $msg['body']['message'];
    		$msg['body']['message'] = null;
    		$msg['body']['message'][0] = $tmp;
    	}
    	return $msg['body'];
    }
    
    /**
    * 接收消息的用户
    * @param    string $user    
    * @return   int
    */
    public function setTo($user)
    {
    	$this->_to = $user;
    	return $this;
    }
    
    /**
    * 设定当前使有的用户名及密码
    * @param    int $username    
    * @param    int $password    
    * @return   int
    */
    public function setAccout($username, $password)
    {
    	$this->_username = $username;
    	$this->_password = $password;
    	return $this;
    }
    
    /**
     * 构造XML代码 
     */
    private function _xml($type){
    	$xml = "<body function=\"".$type."\">";
    	$xml .= "<username>".$this->_username."</username>";
    	$xml .= "<password>".$this->_password."</password>";
    	$xml .= "<to>".$this->_to."</to>";
    	switch ($type){
    		case "send":
    			$xml .= "<message>".$this->_message."</message>";
    			break;
    		case "receive":    			
    			break;
    		case "roster":
    			$xml .= "<status>all</status>";
    			break;
    		default:
    			return null;
    	}
    	$xml .= "</body>";
    	return $xml;
    }
    
    /**
     * 发送XML代码 
     * @return string XML 服务器返回状态
     */
    private function _send($xml){
    	Logger::info($xml);
    	$client = new Zend_Http_Client($this->_url);
    	$client->setMethod(Zend_Http_Client::POST);
    	$client->setRawData($xml);
    	$response = $client->request();
    	Logger::info($response->getBody());
    	return $response->getBody();
    }
    
    /**
     * 解析XML 
     * @return array;
     */
    private function _parseXML($xml){
    	 return Zend_Json::decode(Zend_Json::fromXml($xml));
    }
}
